package cloud.misiro.spring.cloud.zuul.filters.post;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

import static cloud.misiro.spring.cloud.zuul.filters.support.FilterConstants.POST_TYPE;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

public class SendResponseFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(SendResponseFilter.class);

    @Override
    public String filterType() {
        return POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1000;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().getResponseDataStream() != null;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        InputStream inputStream = requestContext.getResponseDataStream();

        try {
            HttpServletResponse servletResponse = requestContext.getResponse();
            servletResponse.setCharacterEncoding("UTF-8");

            OutputStream outputStream = servletResponse.getOutputStream();
            StreamUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            rethrowRuntimeException(e);
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    logger.error("关闭输入流失败", e);
                }
            }
        }
        return null;
    }
}
